#!/bin/bash

set -Eeuo pipefail
shopt -s inherit_errexit

npm install -g @sourcegraph/scip-python

PIP_DIR=$(mktemp -d)
trap 'rm -rf "${PIP_DIR}"' EXIT

# json5 has a multiline license field that breaks everything
# https://github.com/sourcegraph/scip-python/issues/157
pip3=$(command -v pip3)
cat > "${PIP_DIR}/pip3" << EOF
#!/bin/bash

set -Eeuo pipefail
shopt -s inherit_errexit

if (( \$# > 0 )) && [[ \$1 == show ]]; then
    # only keep Name/Version/Files fields
    "${pip3}" "\$@" | sed -nE '/^(Name|Version):/{p;b};/^Files:$/,/^[^ ]/{p;b};/^Files:$/,\${p;b}'
else
    exec "${pip3}" "\$@"
fi
EOF
chmod +x "${PIP_DIR}/pip3"

PATH=${PIP_DIR}:${PATH} scip-python index

arch=$(arch | sed s/x86_64/amd64/)
curl --location "https://github.com/sourcegraph/scip/releases/latest/download/scip-linux-${arch}.tar.gz" | tar xzf - scip

./scip convert --from index.scip --to dump.lsif
